package jpb.security;

import jpb.constant.StatusCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;


/**
 * Created by haol on 2017/3/16.
 */
public class HandleCookie {

 private static Logger logger = LoggerFactory.getLogger(HandleCookie.class);



        public static HttpServletResponse saveCookie(HttpServletResponse response,
                                                     String cookieName,String cookieValue){

                Cookie cookie = new Cookie(cookieName, cookieValue);
                cookie.setHttpOnly(true);
                cookie.setPath("/");
                try {
                        URLEncoder.encode(cookieValue, "utf-8");
                } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                }
                response.addCookie(cookie);
               // logger.info("保存cookie到本地,name =[{}]",cookieName);
                return response;
        }
        public static HttpServletResponse deleteCookie(HttpServletResponse response,String name){
                Cookie cookie = new Cookie(name, null);
                cookie.setMaxAge(0);
                cookie.setPath("/");
                response.addCookie(cookie);
                return response;
        }
        public static Cookie getCookieByName(HttpServletRequest request, String name){
                Cookie[] cookies = request.getCookies();
                Cookie cookie = null;
                for (Cookie cookie_ :cookies){
                        if (cookie_.getName().equals(name)){
                                cookie = cookie_;
                        }
                }
                return cookie;
        }
        public static String getValueByName(HttpServletRequest request, String name){
                Cookie cookie = getCookieByName(request,name);
                return cookie.getValue();
        }

        public static HttpServletResponse updateCookie(String subject, HttpServletResponse response, Date IssuedTime,String cookieName){
                ProduceJwt produceJwt = new ProduceJwt();
                String jwt = produceJwt.produceWebToken(subject,
                        StatusCode.JWT_ID, StatusCode.JWT_WEB_TTL,IssuedTime);
               // logger.info("更新cookie到本地,name =[{}],value=[{}]");
                return HandleCookie.saveCookie(response,cookieName,jwt);
        }

}


